
const { Menu,dialog } = require('electron')

const got = require('got').default

const path = require('path')

const imageType = require('image-type')

const randomstring = require('randomstring')

const fs = require('fs')


const saveas = async  (saveUrl) => {
    if (saveUrl) {
        const contextMenu = Menu.buildFromTemplate([
            {
                label:'图片另存为...',
                // 绑定点击事件
                click: () => {
                    got.get(saveUrl).then(async (response) => {
                        //获取到响应的原始数据,然后将数据转成流
                        const chunk = Buffer.from(response.rawBody)
                        

                        //可以获取到图片的后缀信息
                        const imgType = imageType(chunk)
                        

                        const { filePath,canceled } = await dialog.showSaveDialog({
                            title:"图片另存为",
                            defaultPath:path.resolve(__dirname,'../public/uploads/' + randomstring.generate(10) + '.' + imgType.ext)
                        })

                        if(!canceled) {
                            //filepath其实指向一个文件
                            //将流chunk写入文件，
                            fs.writeFileSync(filePath,chunk)
                        }


                    }).catch((e) => {}) 

                    
                },
                //定义快捷键
                accelerator:'CommandOrControl+S'
            }
        ])

        //弹出菜单
        contextMenu.popup()
    }


}


module.exports = saveas